package core.jfinal.ext.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/3/16.
 */
public class BaseController extends Controller {
    private static String REGEX = "(([a-zA-Z][a-zA-Z0-9]*(\\[[0-9]+\\])?)\\.)*([a-zA-Z][a-zA-Z0-9]*(\\[[0-9]+\\])?)";

    public Record getParaData() {
        Map<String, String[]> paraMap = getParaMap();
        Map<String, Object> root = new HashMap();
        Iterator i$ = paraMap.entrySet().iterator();


        while (i$.hasNext()) {
            Entry entry = (Entry) i$.next();
            String key = (String) entry.getKey();
            String[] value = (String[]) entry.getValue();

            //判断key是否符合要求
            if (!isTrueKey(key)) {
                throw new RuntimeException("[" + key + "]格式不匹配");
            }
            Object tempRoot = root;
            Pattern p = Pattern.compile("([a-zA-Z][a-zA-Z0-9]*)(\\[([0-9]+)\\])?\\.?");
            Matcher m2 = p.matcher(key);
            while (m2.find()) {
                //获取不包含点的key
                String k = m2.group(1);
                //获取key后面跟着的索引 没有则为null
                Integer arrayIndex = m2.group(3) != null ? Integer.parseInt(m2.group(3)) : null;
                //无索引的情况,新建一个Map  在父Map上插入{key:k value:新建的Map}
                //有索引的情况,新建List     在父Map上插入{key:k value:新建的List}
                if (arrayIndex == null) {
                    //获取父Map里k对应的Map
                    Map map = (Map) ((Map) tempRoot).get(k);
                    //匹配的k是最后一个了
                    if (m2.hitEnd()) {
                        ((Map) tempRoot).put(k, value.length == 1 ? value[0] : Arrays.asList(value));
                        break;
                    }
                    //获取父Map里k对应的值  没有的话新建一个Map放进去
                    if (((Map) tempRoot).get(k) == null) {
                        ((Map) tempRoot).put(k, new HashMap());
                        map = (Map) ((Map) tempRoot).get(k);
                    }
                    //父Map更改为k对应的Map
                    tempRoot = map;
                } else {
                    //获取父Map里k对应的List
                    List list = (List) (((Map) tempRoot).get(k));
                    //没有的话新建一个  有的话,判断有没有索引arrayIndex这个位置 没的话 补
                    if (list == null) {
                        List arr = new ArrayList();
                        for (int i = 0; i <= arrayIndex; i++)
                            arr.add(new HashMap());
                        ((Map) tempRoot).put(k, arr);
                        list = (List) (((Map) tempRoot).get(k));
                    } else if (list.size() <= arrayIndex) {
                        for (int i = list.size(); i <= arrayIndex; i++)
                            list.add(new HashMap());
                    }
                    //匹配的k是最后一个了 在k对应的List中设值
                    if (m2.hitEnd()) {
                        list.set(arrayIndex, value.length == 1 ? value[0] : Arrays.asList(value));
                        break;
                    }
                    //父Map更改为 父Map里k对应的List里的arrayIndex位置的Map
                    tempRoot = list.get(arrayIndex);
                }

            }
        }
        return new Record().setColumns(root);
    }

    private static boolean isTrueKey(String key) {
        //匹配格式 (([a-zA-Z][a-zA-Z0-9]*(\[[0-9]+\])?)\.)*([a-zA-Z][a-zA-Z0-9]*(\[[0-9]+\])?)
        Pattern p = Pattern.compile(REGEX);
        Matcher m1 = p.matcher(key);

        return m1.matches();


    }


    public Map getParaMap() {
        Map paraMap = super.getParaMap();
        Map result = new HashMap();
        for (Object key : paraMap.keySet()) {
            Object value = paraMap.get(key);
            if (value instanceof String[]) {
                String[] var2 = (String[]) value;
                if ((var2.length == 1)) {
                    result.put(key, var2[0]);
                }else if(var2.length > 1){
                    result.remove(key);
                    result.put(((String) key).replaceAll("[\\[\\]]",""), value);
                }
            }
        }
        return result;
    }


    //将内部的Record更改为Map
    public Object resolveInnerRecord(Object resource){
        if(resource instanceof Record){
            return resolveInnerRecord(((Record) resource).getColumns());
        } else if (resource instanceof Collection || resource instanceof Map) {
            Iterator iterator;
            if(resource instanceof Collection){
                Collection list = null;
                try {
                    list = (Collection) resource.getClass().newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                iterator = ((Collection) resource).iterator();
                while (iterator.hasNext()){
                    list.add(resolveInnerRecord(iterator.next()));
                }
                return list;
            } else {
                Map map = null;
                try {
                    map = (Map) resource.getClass().newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                Set set = ((Map) resource).keySet();
                iterator = set.iterator();
                while (iterator.hasNext()){
                    Object next = iterator.next();
                    map.put(next ,resolveInnerRecord(((Map) resource).get(next)));
                }
                return map;
            }
        }
        return resource;

    }


}
